/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pub;

import Utils.Static;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.CustomerModel;

/**
 *
 * @author user
 */
public class customer extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession(true);
            if (session.getAttribute(Static.categories) == null) {
                response.sendRedirect("load");
                return;
            }

            ArrayList<String> script = new ArrayList<String>();
            script.add("<script src=\"jscripts/jquery-validate/lib/jquery.js\" type=\"text/javascript\"></script>");
            script.add("<script src=\"jscripts/jquery-validate/jquery.validate.js\" type=\"text/javascript\"></script>");
            script.add("<script src=\"jscripts/customers.js\" type=\"text/javascript\"></script>");
            session.setAttribute(Static.java_script, script);

            String action = request.getParameter(Static.action);
            if (action == null) {
                Index(request, response);
            } else if (action.compareTo("login") == 0) {
                Login(request, response);
            } else if (action.compareTo("logout") == 0) {
                Logout(request, response);
            } else if (action.compareTo("add") == 0) {
                Add(request, response);
            } else if (action.compareTo("recovery") == 0) {
                Recovery(request, response);
            } else if (action.compareTo("edit") == 0) {
                Edit(request, response);
            } else {
                Index(request, response);
            }


        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void Index(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);
            getServletContext().getRequestDispatcher("/pub/customers/index.jsp").forward(request, response);
        } catch (Exception ex) {
        }
    }

    public void Add(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);

            String username = (String) request.getParameter("username");
            String password = (String) request.getParameter("password");
            String check_password = (String) request.getParameter("confirm_password");
            String firstname = (String) request.getParameter("firstname");
            String lastname = (String) request.getParameter("lastname");
            String address = (String) request.getParameter("address");
            String email = (String) request.getParameter("email");
            String district = (String) request.getParameter("district");
            String city = (String) request.getParameter("city");
            String phone = (String) request.getParameter("phone");
            String fax = (String) request.getParameter("fax");
            String postalCode = (String) request.getParameter("postalCode");

            if (username.isEmpty()) {
                throw new Exception("Introduceti numele de utilizator.");
            }
            if (firstname.isEmpty()) {
                throw new Exception("Introduceti username.");
            }

            if (lastname.isEmpty()) {
                throw new Exception("Introduceti prenumele.");
            }

            if (password.isEmpty()) {
                throw new Exception("Introduceti parola.");
            }

            if (password.length() < 5) {
                throw new Exception("Parola trebuie sa aibe cel putin 5 caractere.");
            }

            if (check_password.isEmpty()) {
                throw new Exception("Confirmati parola.");
            }

            if (password.compareTo(check_password) != 0) {
                throw new Exception("Parolele nu coincid.");
            }

            if (!Utils.CheckEmail.Check(email)) {
                throw new Exception("Adresa de email este invalida");
            }

            CustomerModel customerModel = new CustomerModel();

            if (customerModel.AddCustomer(username, password, firstname, lastname, address, district, city, phone, fax, email, postalCode) == -1) {
                session.setAttribute(Static.confirm, customerModel.GetMessage());
                response.sendRedirect("customers");
                return;
            }

            session.setAttribute(Static.confirm, "Contul a fost creat cu succes.");
            response.sendRedirect("customers");
        } catch (Exception ex) {
        }
    }

    public void Edit(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);

        } catch (Exception ex) {
        }
    }

    public void Recovery(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);
            getServletContext().getRequestDispatcher("/pub/customers/recovery.jsp").forward(request, response);
        } catch (Exception ex) {
        }
    }

    public void Login(HttpServletRequest request, HttpServletResponse response) {

        try {
            PrintWriter out = response.getWriter();
            try {

                HttpSession session = request.getSession(true);

                String username = request.getParameter(Static.username);
                String password = request.getParameter(Static.password);


                if (username.isEmpty()) {
                    throw new Exception("Completati utilizator.");
                }
                if (password.isEmpty()) {
                    throw new Exception("Completati parola.");
                }

                CustomerModel customerModel = new CustomerModel();
                HashMap customer = customerModel.ValidateUser(username, password);

                if (customer != null) {
                    out.println("<br /><br /><b style=\"color:#2D7D57;font-size: 12px;\">Sunteti logat ca <b style=\"color: red\">" + customer.get("Username") + "</b></b><br />");
                    out.println("<a onclick=\"Logout()\" class=\"link\" style=\"cursor:pointer\" ><b>&laquo;&nbsp;logout&nbsp;&raquo;</b></a>");
                    session.setAttribute(Static.customer, customer);
                    return;
                } else {
                    throw new Exception(customerModel.GetMessage());
                }
            } catch (Exception ex) {
                out.println("<br /><br /><div id=\"div_error_login\"><label id=\"lb_login_error\"><strong>EROARE</strong>:" + ex.getMessage() + " <br></label></div>");
                out.println("<div><label id=\"lblUser\" name=\"lblUser\" for=\"txtUserName\"> Utilizator </label></div>"
                        + " <div><input id=\"txtUserName\" name=\"txtUserName\" type=\"text\" class=\"input\" size=\"20\" maxlength=\"30\" /></div>"
                        + " <div><label id=\"lblPass\" name=\"lblPass\" for=\"txtpass\"> Parola </label></div>"
                        + " <div><input id=\"txtpass\" name=\"txtpass\" type=\"password\" class=\"input\" onkeypress=\"doClick('login')"
                        + " size=\"20\" maxlength=\"20\" /></div> <div><input name=\"login\" id=\"login\" type=\"submit\" class=\"button\" size=\"30\""
                        + " value=\"Login\" onclick=\"Login()\" /></div><br />"
                        + " <div><a href=\"customers?action=recovery\" class=\"link\"><b>Am uitat parola</b></a></div>"
                        + " <div><a href=\"customers\" class=\"link\"><b>Inregistrare</b></a></div>");
            }
        } catch (Exception ex) {
        }
    }

    public void Logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession(true);

            session.setAttribute(Static.customer, null);
            PrintWriter out = response.getWriter();
            out.println("<br/><br/><div id=\"div_error_login\"></div>"
                    + " <div><label id=\"lblUser\" name=\"lblUser\" for=\"txtUserName\"> Utilizator </label></div>"
                    + " <div><input id=\"txtUserName\" name=\"txtUserName\" type=\"text\""
                    + " class=\"input\" size=\"20\" maxlength=\"30\" /></div>"
                    + " <div><label id=\"lblPass\" name=\"lblPass\" for=\"txtpass\"> Parola </label></div>"
                    + " <div><input id=\"txtpass\" name=\"txtpass\" type=\"password\" class=\"input\" onkeypress=\"doClick(\'login\')\""
                    + " size=\"20\" maxlength=\"20\" /></div><div><input name=\"login\" id=\"login\" type=\"submit\" class=\"button\" size=\"30\""
                    + " value=\"Login\" onclick=\"Login()\" /></div><br />"
                    + " <div><a href=\"customers?action=recovery\" class=\"link\"><b>Am uitat parola</b></a></div>"
                    + " <div><a href=\"customers\" class=\"link\"><b>Inregistrare</b></a></div>");
        } catch (Exception ex) {
        }
    }
}
